package com.jvm123.excel.common;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class DefaultExcelReader implements ExcelReader {

    private static final Logger logger = LoggerFactory.getLogger(DefaultExcelReader.class);

    @Override
    public Workbook read(InputStream inputStream) {
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            try {
                workbook = new HSSFWorkbook(inputStream);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return workbook;
    }

    @Override
    public Workbook read(File file) {
        Workbook workbook = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            workbook = read(fis);
        } catch (IOException e) {
            logger.error("读取文件失败：{}", file);
        }
        logger.debug("读取文件“{}”完毕", file.getAbsoluteFile());
        return workbook;
    }

    @Override
    public Workbook read(String filePath) {
        if (filePath == null || filePath.equals("")) {
            return null;
        }

        Workbook workbook = null;
        String extStr = filePath.substring(filePath.lastIndexOf("."));
        try (InputStream is = new FileInputStream(filePath)) {
            if (".xls".equals(extStr)) {
                workbook = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extStr)) {
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            logger.error("读取文件失败：{}", filePath);
        }
        logger.debug("读取文件“{}”完毕", filePath);
        return workbook;
    }
}
